package com.gitee.cashzhang27.test.boot.functional.error;

import org.springframework.http.HttpStatus;
import org.springframework.web.client.RestClientException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.function.ServerRequest;
import org.springframework.web.servlet.function.ServerResponse;

/**
 * 异常处理助手.
 *
 * @author Cash Zhang
 * @version v1.0 2020/09/16 10:27
 * @since v1.0
 */
public class ExceptionHandlerHelper {

  public static ServerResponse handlerError(Throwable ex, ServerRequest request) {
    HttpStatus httpStatus;
    ExceptionEntity exceptionEntity;
    if (ex instanceof ResponseStatusException) {
      ResponseStatusException responseStatusException = (ResponseStatusException) ex;
      httpStatus = responseStatusException.getStatus();
      switch (httpStatus) {
        case BAD_REQUEST:
          exceptionEntity =
              ExceptionEntity.builder()
                  .errorCode("INVALID_PARAMETER")
                  .errorDesc("参数无效")
                  .solution("检查请求参数，修改后重新发起请求")
                  .build();
          break;
        default:
          exceptionEntity = ExceptionEntity.builder().build();
      }
    } else if (ex instanceof RestClientException) {
      httpStatus = HttpStatus.MULTI_STATUS;
      exceptionEntity = ExceptionEntity.builder().build();
    } else {
      httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
      exceptionEntity = ExceptionEntity.builder().exceptionClass(ex.getClass().toString()).build();
    }
    return ServerResponse.status(httpStatus).body(exceptionEntity);
  }

}
